import React, { useRef, useEffect } from 'react';
import { IonList, IonContent } from '@ionic/react';
import { useChatStore } from '../../store/chat';
import ChatMessage from './ChatMessage';

interface ChatMessagesProps {
  isSpeakerOn: boolean;
}

const ChatMessages: React.FC<ChatMessagesProps> = ({ isSpeakerOn }) => {
  const { histories, currentService } = useChatStore();
  const messages = histories[currentService] || [];
  const contentRef = useRef<HTMLIonContentElement>(null);

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.scrollToBottom(500);
    }
  }, [messages]);

  return (
    <IonContent ref={contentRef} scrollEvents={true}>
      <IonList className="ion-padding">
        {messages.map((message) => (
          <ChatMessage
            key={message.id}
            text={message.text}
            isBot={message.isBot}
            isSpeakerOn={isSpeakerOn}
          />
        ))}
      </IonList>
    </IonContent>
  );
};

export default ChatMessages;